package com.jerome.fs.storage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * File utility class.
 *
 * @author Jerome
 * @date 2023/8/7
 */
public class FileUtil {

    /**
     * Writes a string to a file.
     *
     * @param fileName The system-dependent filename.
     * @param content  String to be written to the file.
     * @param append   If <code>true</code>, data will be written to the end of the file; otherwise, it will overwrite the file.
     * @throws IOException if an I/O error occurs.
     */
    public static synchronized void write2File(String fileName, String content, boolean append) throws IOException {
        try (BufferedWriter out = new BufferedWriter(new FileWriter(fileName, append))) {
            out.write(content);
        }
    }

    /**
     * Reads the contents of a file.
     *
     * @param fileName The name of the file to read from.
     * @return The content of the file as a string.
     * @throws IOException if an I/O error occurs.
     */
    public static synchronized String readFile(String fileName) throws IOException {
        try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        }
    }


    /**
     * Serialize an object to a file.
     *
     * @param object   The object to be serialized.
     * @param fileName The file where the object will be stored.
     * @throws IOException if an I/O error occurs.
     */
    public static void serialize(Object object, String fileName) throws IOException {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(fileName)))) {
            objectOutputStream.writeObject(object);
        }
    }

    /**
     * Deserialize an object from a file.
     *
     * @param fileName The file from which the object will be deserialized.
     * @return The deserialized object.
     * @throws IOException            if an I/O error occurs.
     * @throws ClassNotFoundException if the class of the object cannot be found.
     */
    public static Object deserialize(String fileName) throws IOException, ClassNotFoundException {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(fileName)))) {
            Object object = objectInputStream.readObject();
            return object;
        }
    }
}
